package cn.com.anypay.manager.common.config;

import cn.com.anypay.manager.common.annotation.IgnoreResponseAdvice;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.nio.charset.StandardCharsets;

/**
 * 响应编码处理器
 * 确保所有JSON响应都使用UTF-8编码
 */
@RestControllerAdvice
public class ResponseEncodingAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查是否需要忽略响应处理
        if (returnType.hasMethodAnnotation(IgnoreResponseAdvice.class) ||
            returnType.getContainingClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // 确保JSON响应使用UTF-8编码
        if (selectedContentType != null && selectedContentType.includes(MediaType.APPLICATION_JSON)) {
            response.getHeaders().setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
        }

        return body;
    }
}